package com.mask.mr.demo;

import java.io.IOException;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;

public class Temperatuer {

	static class TemperatuerMapper extends Mapper<LongWritable,Text,Text,IntWritable>{
		@Override
		protected void map(LongWritable key, Text value, Mapper<LongWritable, Text, Text, IntWritable>.Context context)
				throws IOException, InterruptedException {
			//1.获取文本中的一行数据，将其转换成java对应的字符串
			String line = value.toString();
			//2021092631
			//2.字符串截取年份
			String year = line.substring(0,4);
			//3.字符串截取温度
			int temp = Integer.parseInt(line.substring(8));
			//4.生成key-value，然后输出context
			context.write(new Text(year), new IntWritable(temp));
		}
	}
	
	static class TemperatuerReducer extends Reducer<Text, IntWritable, Text, IntWritable>{
		@Override
		protected void reduce(Text key, Iterable<IntWritable> values,
				Reducer<Text, IntWritable, Text, IntWritable>.Context context) throws IOException, InterruptedException {

			int minTemp = Integer.MAX_VALUE;
			
			for(IntWritable value :values) {
				minTemp = Integer.min(minTemp, value.get());
			}
			context.write(new Text(key),new IntWritable(minTemp));
		}
	}
	
	public static void  main(String[] args) throws Exception {
		//1.获取Job对象，来处理MapReduce
		Configuration conf = new Configuration();
		Job job = Job.getInstance(conf);
		
		//2.获取数据文件
		String inPath  = "/Users/hx/Documents/massz.edu.cn/bigData/data_project/input";//在定义路径时只需到文件夹就可以，不需要写出文件
		String outPath  = "/Users/hx/Documents/massz.edu.cn/bigData/data_project/output";//输出文件夹必须不存在，需要程序自己创建
		FileInputFormat.setInputPaths(job, new Path(inPath));
		
		
		//3.相关的配置--Map和Reduce程序
		job.setMapperClass(TemperatuerMapper.class);
		job.setReducerClass(TemperatuerReducer.class);
		
		//设置Map的输出结果
		job.setMapOutputKeyClass(Text.class);
		job.setMapOutputValueClass(IntWritable.class);
		
		//设置Reduce的输出结果
		job.setOutputKeyClass(Text.class);
		job.setOutputValueClass(IntWritable.class);
		
		//4.输出运行结果
		FileOutputFormat.setOutputPath(job, new Path(outPath));
		
		//5.结束程序
		boolean res = job.waitForCompletion(true);
		
		System.exit(res?0:1);
	}
	
	
}
